import requests
import json
import os
import re

from PIL import Image, ImageDraw,ImageFont
from barcode import Code128
from barcode.writer import ImageWriter
import qrcode
# 定义图像大小和条形码大小
image_width = 2479
image_height = 3508
qrcode_size = 400


def search_save_and_return(sn):
    begin_url="https://pro-psurf-app.glb.inc.hp.com/partsurferapi/Search/GenericSearch/"+sn+"/country/CN/usertype/EXT"
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'Authorization': 'Basic MjAyMzEzNy1wYXJ0c3VyZmVyOlBTVVJGQCNQUk9E',
        'Connection': 'keep-alive',
        'Host': 'pro-psurf-app.glb.inc.hp.com',
        'Origin': 'https://partsurfer.hp.com',
        'Referer': 'https://partsurfer.hp.com/',
        #'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
        #'sec-ch-ua-mobile': '?0',
        #'sec-ch-ua-platform': '"Windows"',
        #'Sec-Fetch-Dest': 'empty',
        #'Sec-Fetch-Mode': 'cors',
        #'Sec-Fetch-Site': 'same-site',
        #'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'

        }
    r = requests.get(begin_url,headers=headers)
    jsdata={}
    if(r.status_code==200):
        htmlx_byt=r.content
        htmlx=str(htmlx_byt,'utf-8')
        jsdata=json.loads(htmlx)
        datacode=jsdata['Status']['Code']
        if(datacode=='S-0001'):
            f=open("database/"+sn+".json","w")
            f.write(json.dumps(jsdata, indent=4, separators=(',', ': ')))
            f.close
            print("saved")
        elif(datacode=='E-0099'):
            jsdata={}
            print("can not seach the sn")
    else:
        print("web error")
    return jsdata



print("HP partsurfer auto get BuildId and FeatureByte. V1.9")
print("compiled by kevin. wuwenfengmi@outlook.com")
print("for learning purposes only")
if not os.path.exists("database/"):
    os.makedirs("database/")
while_loop=True
while while_loop:
    print("Enter Serial No.\nor Enter (exit)")
    HP_device_SN=input(":")
    if HP_device_SN=="exit":
        while_loop=False
    else:
        jdata={}
        if os.path.exists("database/"+HP_device_SN+".json"):
            print("fined in database")
            f=open("database/"+HP_device_SN+".json","r")
            jdata=json.loads(f.read())
        else:
            print("find in wed")
            jdata=search_save_and_return(HP_device_SN)

        if jdata!={}:
            try:
                sn=jdata['Body']['SerialNumberBOM']['wwsnrsinput']['serial_no']
                pn=jdata['Body']['SerialNumberBOM']['wwsnrsinput']['product_no']
                dn=jdata['Body']['SerialNumberBOM']['wwsnrsinput']['user_name']
                print("------------------------------------------------")
                print("Serial No: "+sn)
                print("Product No: "+pn)
                print("Device Name: "+dn)
                print("---")
                unit_data=jdata['Body']['SerialNumberBOM']['unit_configuration']
                for i in unit_data:
                    if i['part_number'].lower()=="IMG_BuildId".lower():
                        bilid=str(i['part_description']).replace("BID=","")
                    if i['part_number'].lower()=="IMG_Desc1".lower():
                        Desc1=i['part_description']
                    if i['part_number'].lower()=="IMG_Desc2".lower():
                        Desc2=i['part_description']
                FeatureByte=Desc1+Desc2
                FeatureByte=str(FeatureByte).replace(" ","")
                print("Build Id: "+bilid)
                print("Feature Byte: "+FeatureByte)
                #print("Feature Byte 4: ")
                fb2=""
                index=0
                for i in FeatureByte:
                    if index==4:
                        index=0
                        #print(" ",end="")
                        fb2+=" "
                    index+=1
                    #print(i,end="")
                    fb2+=i
                
                print(fb2)
                print("\n------------------------------------------------\n\n")

                #cp
                # 创建一个空白图像
                image = Image.new("RGB", (image_width, image_height), (255, 255, 255))
                draw = ImageDraw.Draw(image)

                # 条形码配置
                barcode_options = {
                    "writer": ImageWriter(),
                    "output": 'temp',  # 输出格式，可以是文件名或字节流
                }



                # 在图像上生成多个条形码并放置它们
                x_position = 50
                y_position = 50

                # 加载自定义图片并将其添加到图像中
                custom_image = Image.open("favicon.png")  # 替换为你自己的图片路径
                image.paste(custom_image, (x_position, y_position))

                y_position+=150

                # 在条形码下方添加自定义文本
                text_color = (0, 0, 0)  # 文本颜色（黑色）
                # 设置字体大小
                font_size = 20
                font_20 = ImageFont.truetype("fonts/arial", font_size)  # 替换为你自己的字体文件路径
                # 创建一个Draw对象并将文本添加到图像上
                text_draw = ImageDraw.Draw(image)
                text_draw.text((x_position, y_position), "HP partsurfer auto get BuildId and FeatureByte. V1.9\ncompiled by kevin. wuwenfengmi@outlook.com", fill=text_color, font=font_20)

                y_position+=200


                # 在条形码下方添加自定义文本
                text_color = (0, 0, 0)  # 文本颜色（黑色）
                # 设置字体大小
                font_size = 50
                font = ImageFont.truetype("fonts/arial", font_size)  # 替换为你自己的字体文件路径
                # 创建一个Draw对象并将文本添加到图像上
                text_draw = ImageDraw.Draw(image)
                text_draw.text((x_position, y_position), "Serial No: "+sn, fill=text_color, font=font)

                y_position+=50

                # 生成条形码
                barcode = Code128(sn, writer=barcode_options["writer"])
                barcode_file = barcode.save(barcode_options["output"])
                # 打开生成的条形码图像
                barcode_image = Image.open(barcode_file)
                # 将条形码添加到图像上
                image.paste(barcode_image, (x_position, y_position))

                # 更新下一个条形码的位置
                y_position +=  400


                # 创建一个Draw对象并将文本添加到图像上
                text_draw = ImageDraw.Draw(image)
                text_draw.text((x_position, y_position), "Product No: "+pn, fill=text_color, font=font)

                y_position+=50

                # 生成条形码
                barcode = Code128(pn, writer=barcode_options["writer"])
                barcode_file = barcode.save(barcode_options["output"])
                # 打开生成的条形码图像
                barcode_image = Image.open(barcode_file)
                # 将条形码添加到图像上
                image.paste(barcode_image, (x_position, y_position))

                # 更新下一个条形码的位置
                y_position +=  400


                # 创建一个Draw对象并将文本添加到图像上
                text_draw = ImageDraw.Draw(image)
                text_draw.text((x_position, y_position), "Device Name: "+dn, fill=text_color, font=font)

                y_position+=50

                # 生成二维码
                qr = qrcode.QRCode(
                    version=1,
                    error_correction=qrcode.constants.ERROR_CORRECT_L,
                    box_size=10,
                    border=4,
                )
                qr.add_data(dn)
                qr.make(fit=True)
                qr_image = qr.make_image(fill_color="black", back_color="white").resize((qrcode_size, qrcode_size))
                # 将二维码添加到图像上
                image.paste(qr_image, (x_position, y_position))


                # 生成条形码
                barcode = Code128(dn, writer=barcode_options["writer"])
                barcode_file = barcode.save(barcode_options["output"])
                # 打开生成的条形码图像
                barcode_image = Image.open(barcode_file)
                # 将条形码添加到图像上
                image.paste(barcode_image, (x_position+600, y_position+50))

                # 更新下一个条形码的位置
                y_position +=  600



                # 创建一个Draw对象并将文本添加到图像上
                text_draw = ImageDraw.Draw(image)
                text_draw.text((x_position, y_position), "Build Id: "+bilid, fill=text_color, font=font)

                y_position+=50

                # 生成二维码
                qr = qrcode.QRCode(
                    version=1,
                    error_correction=qrcode.constants.ERROR_CORRECT_L,
                    box_size=10,
                    border=4,
                )
                qr.add_data(bilid)
                qr.make(fit=True)
                qr_image = qr.make_image(fill_color="black", back_color="white").resize((qrcode_size, qrcode_size))
                # 将二维码添加到图像上
                image.paste(qr_image, (x_position, y_position))


                # 生成条形码
                barcode = Code128(bilid, writer=barcode_options["writer"])
                barcode_file = barcode.save(barcode_options["output"])
                # 打开生成的条形码图像
                barcode_image = Image.open(barcode_file)
                # 将条形码添加到图像上
                image.paste(barcode_image, (x_position+600, y_position+50))


                # 更新下一个条形码的位置
                y_position +=  600

                # 创建一个Draw对象并将文本添加到图像上
                text_draw = ImageDraw.Draw(image)
                text_draw.text((x_position, y_position), "Feature Byte: "+fb2, fill=text_color, font=font)

                y_position+=50

                # 生成二维码
                qr = qrcode.QRCode(
                    version=1,
                    error_correction=qrcode.constants.ERROR_CORRECT_L,
                    box_size=10,
                    border=4,
                )
                qr.add_data(FeatureByte)
                qr.make(fit=True)
                qr_image = qr.make_image(fill_color="black", back_color="white").resize((qrcode_size, qrcode_size))
                # 将二维码添加到图像上
                image.paste(qr_image, (x_position, y_position))

                # 生成条形码
                barcode = Code128(FeatureByte, writer=barcode_options["writer"])
                barcode_file = barcode.save(barcode_options["output"])
                # 打开生成的条形码图像
                barcode_image = Image.open(barcode_file)
                # 将条形码添加到图像上
                image.paste(barcode_image, (x_position+150, y_position+500))

                # 更新下一个条形码的位置
                y_position +=  400

                # 创建一个Draw对象并将文本添加到图像上
                text_draw = ImageDraw.Draw(image)
                text_draw.text((x_position, y_position), FeatureByte, fill=text_color, font=font)
                # 保存生成的图像
                filename="database/"+sn+".png"
                image.save(filename)

                #try print
                pilfile=Image.open(filename)
                pilfile.show()

                

            except:
                print("Data Error")
        else:
            print("Data Error 2")
print("Thank for use. pass any key..")
os.system('pause')

                

